import 'dart:async';

import 'package:flutter_hx/base/utils/toast_utils.dart';
import 'package:flutter_hx/network/HttpGo.dart';
import 'package:flutter_hx/services/user_service.dart';
import 'package:get/get.dart';

class PayPasswordLogic extends GetxController {
  bool _goodToSave = false;
  bool _smsSent = false;
  bool _smsLock = false;

  ///重新发送倒计时
  int _smsCountDown = 60;
  Timer? _countDownTimer;

  String _payPass = "";
  String _confirmPayPass = "";
  String _verifyCode = "";

  get smsCountDown => _smsCountDown;

  get goodToSave => _goodToSave;

  get smsLock => _smsLock;

  set pass(String pass) {
    _payPass = pass;
    checkGoodToSet();
  }

  set confirmPass(String confirmPass) {
    _confirmPayPass = confirmPass;
    checkGoodToSet();
  }

  set verifyCode(String verifyCode) {
    _verifyCode = verifyCode;
    checkGoodToSet();
  }

  ///检查是否可以进行保存
  checkGoodToSet() {
    if (_payPass.isNotEmpty &&
        _confirmPayPass.isNotEmpty &&
        _verifyCode.isNotEmpty &&
        _smsSent) {
      _goodToSave = true;
      update();
    }
  }

  ///发送验证码
  getSmsCode() async {
    if (_smsLock) {
      return;
    }
    final res = await HttpGo.instance.get("/sms/code",
        params: {"phone": UserService.to.user.value?.phone, "bizType": 3});
    res.ifSuccess((data) {
      ToastUtils.show("短信验证码发送成功");
      _smsSent = true;
      _smsLock = true;
      update();
    });
    res.ifFailure((e) => e.toast());
  }

  ///初始化发送后的倒计时
  initSmsCountDown() {
    _smsCountDown = 60;
    _countDownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_smsCountDown == 0) {
        timer.cancel();
        _countDownTimer = null;
        _smsLock = false;
        update();
      } else {
        _smsCountDown--;
        update();
      }
    });
  }

  ///保存
  savePayPassword() async {
    if (_payPass != _confirmPayPass) {
      return ToastUtils.show("两次支付密码不一致，请重新输入");
    }
    if (_payPass.length < 6 || _payPass.length > 12) {
      return ToastUtils.show("密码需6-12位数数字或字母");
    }
    final res = await HttpGo.instance.post("/member/password", data: {
      "password": _payPass,
      "smsCode": _verifyCode,
      "type": 3,
      "phone": UserService.to.user.value?.phone,
    });
    res.ifSuccess((data) {
      ToastUtils.show("修改支付密码成功");
      Get.back();
    });
    res.ifFailure((e) => e.toast());
  }

  @override
  void onClose() {
    _countDownTimer?.cancel();
    _countDownTimer = null;
    super.onClose();
  }
}
